package wechat.base.snd

import org.apache.log4j.Logger
import org.json.JSONObject
import wechat.base.snd.encoding.JsonPut
import wechat.base.snd.util.ExecPost

import static wechat.base.snd.DepartmentManager.*
import org.eclipse.xtend.lib.annotations.Accessors

class DepartmentManager {
	static String WECHAT_DEPARTMENT_URL = "https://qyapi.weixin.qq.com/cgi-bin/department/create?access_token=";
//	static DepartmentManager departmentManager = new DepartmentManager(WCApplicationFactory::customerApp.token)
	static Logger logger = Logger::getLogger("DepartmentManager")
	
	def static getDepartmentManager(){
		departmentManager
	}

	@Accessors  String token;

	new (String token){
		this.token = token
	}
	def getDepartmentUrl(){
		WECHAT_DEPARTMENT_URL + this.token
	}
	boolean ret = true
	def boolean addDepartment(Department d){
		logger.info('url is '+ departmentUrl)
		logger.info('json string is '+d.jsonBuilder.toString)
		
		
		ExecPost::excuteJsonPost(departmentUrl, d.jsonBuilder.toString)=>[
			new JSONObject(it)=>[
				logger.info("Add department return code is "+ it.getString("errcode"))		
				ret =  it.getString('errcode').equals('0')
				d.id = it.getString('id')
			]
		]
//		val JSONObject jsResponse =  new JSONObject(ExecPost::excuteJsonPost(departmentUrl, d.jsonBuilder.toString))
//		d=>[ id = jsResponse.getString('id')]
//		jsResponse.getString('errcode').equals('0')
		ret
	}
}
class Department{
	@Accessors  String name;
 	@Accessors String parentid;
	@Accessors String order;
	@Accessors String id;
	new (String name, String parentid){
		this.name = name
		this.parentid = parentid
	}
	def JSONObject jsonBuilder(){
		new JsonPut()=>[
			putObj('name',name)
			putObj('parentid',parentid)
			putObj('order',order)
			putObj('id',id)
		]
	}
}
//class DepartmentList{
//	ErrorMsg resCode;
//	JSONArray departmentList
//	
//}